package com.myc.train.${module}.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myc.train.common.resp.PageResp;
import com.myc.train.common.utils.SnowUtil;
import com.myc.train.${module}.domain.${Domain};
import com.myc.train.${module}.domain.${Domain}Example;
import com.myc.train.${module}.mapper.${Domain}Mapper;
import com.myc.train.${module}.req.${Domain}QueryReq;
import com.myc.train.${module}.req.${Domain}SaveReq;
import com.myc.train.${module}.resp.${Domain}QueryResp;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ${Domain}Service {

    @Resource
    private ${Domain}Mapper ${domain}Mapper;

    public void save(${Domain}SaveReq req){
        DateTime now = DateTime.now();
        ${Domain} ${domain} = BeanUtil.copyProperties(req, ${Domain}.class);

        if(ObjectUtil.isNull(${domain}.getId())){
            ${domain}.setId(SnowUtil.getSnowflakeNextId());
            ${domain}.setCreateTime(now);
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.insert(${domain});
        }else{
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.updateByPrimaryKey(${domain});
        }
    }

    public PageResp<${Domain}QueryResp> queryList(${Domain}QueryReq req){
       //定义查询条件
        ${Domain}Example ${domain}Example = new ${Domain}Example();
        //根据id倒序排序
        ${domain}Example.setOrderByClause("id desc");
        //创建查询对象
        ${Domain}Example.Criteria criteria = ${domain}Example.createCriteria();
        //不为空则对其新增查询条件


        //新增分页信息
        PageHelper.startPage(req.getPage(),req.getSize());
        //根据条件查询结果
        List<${Domain}> ${domain}s = ${domain}Mapper.selectByExample(${domain}Example);
        //new一个PageInfo并将结果放进来
        PageInfo<${Domain}> ${domain}PageInfo = new PageInfo<>(${domain}s);
        //类拷贝
        List<${Domain}QueryResp> queryResps = BeanUtil.copyToList(${domain}s, ${Domain}QueryResp.class);
        //new一个PageResp
        PageResp<${Domain}QueryResp> resp= new PageResp<>();
        //放数据
        resp.setTotal(${domain}PageInfo.getTotal());
        resp.setList(queryResps);


        return resp;
    }

    public void delete(Long id){
        ${domain}Mapper.deleteByPrimaryKey(id);
    }


}
